package handConsistentHash;

import consistentHash.ConsistentHashRouter;
import consistentHash.PhysicalNode;

import java.util.Arrays;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author 03010570
 * @date 2020/07/08
 * describe:
 */
public class ConsistentHashTest {
    public static void main(String[] args) {

        //initialize 4 service node
        PNode node1 = new PNode("IDC1", "127.0.0.1", 8080);
        PNode node2 = new PNode("IDC1", "127.0.0.1", 8081);
        PNode node3 = new PNode("IDC1", "127.0.0.1", 8082);
        PNode node4 = new PNode("IDC1", "127.0.0.1", 8084);

        //hash them to hash ring
        ConsistentHashAlgorithm consistentHashRouter = new ConsistentHashAlgorithm(Arrays.asList(node1, node2, node3, node4), 10);//10 virtual node
        SortedMap<String, Long> map = new TreeMap<>();

        int count = 100000;
        for (int i = 0; i < count; i++) {
            String randomIp = IPUtils.getRandomIp();

        }

        //we have 5 requester ip, we are trying them to route to one service node
        String requestIP1 = "192.168.0.1";
        String requestIP2 = "192.168.0.2";
        String requestIP3 = "192.168.0.3";
        String requestIP4 = "192.168.0.4";
        String requestIP5 = "192.168.0.5";

        goRoute(consistentHashRouter, requestIP1, requestIP2, requestIP3, requestIP4, requestIP5);

        PNode node5 = new PNode("IDC2", "127.0.0.1", 8080);//put new service online
        System.out.println("-------------putting new node online " + node5.toString() + "------------");
        consistentHashRouter.addNode(node5, 10);

        goRoute(consistentHashRouter, requestIP1, requestIP2, requestIP3, requestIP4, requestIP5);

        consistentHashRouter.removeNode(node3);
        System.out.println("-------------remove node online " + node3.toString() + "------------");

        goRoute(consistentHashRouter, requestIP1, requestIP2, requestIP3, requestIP4, requestIP5);
    }

    private static void goRoute(ConsistentHashAlgorithm consistentHashRouter, String... requestIps) {
        for (String requestIp : requestIps) {
            System.out.println(requestIp + " is route to " + consistentHashRouter.getNode(requestIp));
        }
    }


}
